package com.ct.ecommerce.gateway.filter;

import com.alibaba.fastjson.JSONObject;
import com.ct.ecommerce.framework.constant.SecurityConstants;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
import java.util.Set;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author changtong
 * @since 2021/6/2
 */
@Component
@Slf4j
public class TokenCheckFilter implements GlobalFilter, Ordered {


    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //取出token
        String token = getUserToken(exchange);
        if (!StringUtils.hasText(token)) {
            //没有token放行，让资源服务器去处理...
            return chain.filter(exchange);
        }

        Boolean hasKay = redisTemplate.hasKey(token);
        if (Objects.nonNull(hasKay) && hasKay) {
            return chain.filter(exchange);
        }
        return builderNoAuthorizationResult(exchange);
    }

    /**
     * 获取token
     *
     * @param exchange
     * @return
     */
    private String getUserToken(ServerWebExchange exchange) {
        String token = exchange.getRequest().getHeaders().getFirst(HttpHeaders.AUTHORIZATION);

        if (StringUtils.hasText(token) && token.indexOf(SecurityConstants.AUTH_TOKEN_FLAG) == 0) {
            return token.replace(SecurityConstants.AUTH_TOKEN_FLAG, "");
        }

        return null;
    }

    /**
     * 构建没有权限的返回提示
     *
     * @return
     */
    private Mono<Void> builderNoAuthorizationResult(ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().set("Content-Type", "application/json");
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        JSONObject responseJson = new JSONObject();
        responseJson.put("error", "NoAuthorization");
        responseJson.put("errorMsg", "Token is null or Error");
        DataBuffer data = response.bufferFactory()
            .wrap(responseJson.toJSONString().getBytes(StandardCharsets.UTF_8));
        return response.writeWith(Mono.just(data));
    }


    @Override
    public int getOrder() {
        return 0;
    }
}
